<template>
  <div class="notifications-container">
    <a-page-header title="Notifications" sub-title="View your messages and notifications"/>
    
    <!-- 未读消息统计 -->
    <div class="custom-unread-alert" v-if="unreadCount > 0">
      <div class="alert-icon">
        <a-badge status="processing" />
      </div>
      <div class="alert-content">
        <div class="alert-title">You have unread messages</div>
        <div class="alert-description">You have {{ unreadCount }} unread messages, please check them promptly</div>
      </div>
    </div>
    
    <a-card class="notifications-content">
      <a-tabs v-model:activeKey="activeTabKey" @change="handleTabChange">
        <a-tab-pane key="all" tab="All Messages">
          <a-list
            itemLayout="horizontal"
            :dataSource="filteredMessages"
            :locale="{ emptyText: 'No messages' }"
            :loading="loading"
          >
            <template #renderItem="{ item }">
              <a-list-item :class="{ 'unread-list-item': item.unread }">
                <a-list-item-meta
                  :title="getMessageTitle(item)"
                >
                  <template #description>
                    <div>
                      {{ getMessageContent(item) }}
                      <span class="message-time">
                        <DateFormatter :value="item.time" />
                      </span>
                    </div>
                  </template>
                  <template #avatar v-if="item.unread">
                    <div class="unread-indicator">
                      <a-badge color="#000" />
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-space>
                    <a-button type="link" class="action-btn" @click="viewMessageDetail(item)">View</a-button>
                  </a-space>
                </template>
              </a-list-item>
            </template>
          </a-list>
          
          <div class="pagination-container" v-if="total > 0">
            <a-pagination
              v-model:current="pagination.page"
              :total="total"
              :pageSize="pagination.pageSize"
              @change="handlePageChange"
              showSizeChanger
              @showSizeChange="handleSizeChange"
              :pageSizeOptions="['10', '20', '50']"
            />
            <div class="total-count">Total {{ total }} messages</div>
          </div>
        </a-tab-pane>
        
        <a-tab-pane key="1" tab="Promotional Messages">
          <a-empty description="No promotional messages" v-if="getMessagesByType('1').length === 0" />
          <a-list
            v-else
            itemLayout="horizontal"
            :dataSource="getMessagesByType('1')"
            :loading="loading"
          >
            <template #renderItem="{ item }">
              <a-list-item :class="{ 'unread-list-item': item.unread }">
                <a-list-item-meta
                  :title="getMessageTitle(item)"
                >
                  <template #description>
                    <div>
                      {{ getMessageContent(item) }}
                      <span class="message-time">
                        <DateFormatter :value="item.time" />
                      </span>
                    </div>
                  </template>
                  <template #avatar v-if="item.unread">
                    <div class="unread-indicator">
                      <a-badge color="#1890ff" />
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-space>
                    <a-button type="link" class="action-btn" @click="viewMessageDetail(item)">View</a-button>
                  </a-space>
                </template>
              </a-list-item>
            </template>
          </a-list>
          <div class="pagination-container" v-if="getMessagesByType('1').length > 0">
            <a-pagination
              v-model:current="pagination.page"
              :total="total"
              :pageSize="pagination.pageSize"
              @change="handlePageChange"
              showSizeChanger
              @showSizeChange="handleSizeChange"
              :pageSizeOptions="['10', '20', '50']"
            />
            <div class="total-count">Total {{ total }} promotional messages</div>
          </div>
        </a-tab-pane>
        
        <a-tab-pane key="2" tab="Order Messages">
          <a-empty description="No order messages" v-if="getMessagesByType('2').length === 0" />
          <a-list
            v-else
            itemLayout="horizontal"
            :dataSource="getMessagesByType('2')"
            :loading="loading"
          >
            <template #renderItem="{ item }">
              <a-list-item :class="{ 'unread-list-item': item.unread }">
                <a-list-item-meta
                  :title="getMessageTitle(item)"
                >
                  <template #description>
                    <div>
                      {{ getMessageContent(item) }}
                      <span class="message-time">
                        <DateFormatter :value="item.time" />
                      </span>
                    </div>
                  </template>
                  <template #avatar v-if="item.unread">
                    <div class="unread-indicator">
                      <a-badge color="#1890ff" />
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-space>
                    <a-button type="link" class="action-btn" @click="viewMessageDetail(item)">View</a-button>
                  </a-space>
                </template>
              </a-list-item>
            </template>
          </a-list>
          <div class="pagination-container" v-if="getMessagesByType('2').length > 0">
            <a-pagination
              v-model:current="pagination.page"
              :total="total"
              :pageSize="pagination.pageSize"
              @change="handlePageChange"
              showSizeChanger
              @showSizeChange="handleSizeChange"
              :pageSizeOptions="['10', '20', '50']"
            />
            <div class="total-count">Total {{ total }} order messages</div>
          </div>
        </a-tab-pane>
        
        <a-tab-pane key="3" tab="Information Messages">
          <a-empty description="No information messages" v-if="getMessagesByType('3').length === 0" />
          <a-list
            v-else
            itemLayout="horizontal"
            :dataSource="getMessagesByType('3')"
            :loading="loading"
          >
            <template #renderItem="{ item }">
              <a-list-item :class="{ 'unread-list-item': item.unread }">
                <a-list-item-meta
                  :title="getMessageTitle(item)"
                >
                  <template #description>
                    <div>
                      {{ getMessageContent(item) }}
                      <span class="message-time">
                        <DateFormatter :value="item.time" />
                      </span>
                    </div>
                  </template>
                  <template #avatar v-if="item.unread">
                    <div class="unread-indicator">
                      <a-badge color="#1890ff" />
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-space>
                    <a-button type="link" class="action-btn" @click="viewMessageDetail(item)">View</a-button>
                  </a-space>
                </template>
              </a-list-item>
            </template>
          </a-list>
          <div class="pagination-container" v-if="getMessagesByType('3').length > 0">
            <a-pagination
              v-model:current="pagination.page"
              :total="total"
              :pageSize="pagination.pageSize"
              @change="handlePageChange"
              showSizeChanger
              @showSizeChange="handleSizeChange"
              :pageSizeOptions="['10', '20', '50']"
            />
            <div class="total-count">Total {{ total }} information messages</div>
          </div>
        </a-tab-pane>
        
        <a-tab-pane key="4" tab="System Messages">
          <a-empty description="No system messages" v-if="getMessagesByType('4').length === 0" />
          <a-list
            v-else
            itemLayout="horizontal"
            :dataSource="getMessagesByType('4')"
            :loading="loading"
          >
            <template #renderItem="{ item }">
              <a-list-item :class="{ 'unread-list-item': item.unread }">
                <a-list-item-meta
                  :title="getMessageTitle(item)"
                >
                  <template #description>
                    <div>
                      {{ getMessageContent(item) }}
                      <span class="message-time">
                        <DateFormatter :value="item.time" />
                      </span>
                    </div>
                  </template>
                  <template #avatar v-if="item.unread">
                    <div class="unread-indicator">
                      <a-badge color="#1890ff" />
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-space>
                    <a-button type="link" class="action-btn" @click="viewMessageDetail(item)">View</a-button>
                  </a-space>
                </template>
              </a-list-item>
            </template>
          </a-list>
          <div class="pagination-container" v-if="getMessagesByType('4').length > 0">
            <a-pagination
              v-model:current="pagination.page"
              :total="total"
              :pageSize="pagination.pageSize"
              @change="handlePageChange"
              showSizeChanger
              @showSizeChange="handleSizeChange"
              :pageSizeOptions="['10', '20', '50']"
            />
            <div class="total-count">Total {{ total }} system messages</div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    
    <!-- Message Detail Drawer -->
    <a-drawer
      :open="drawerVisible"
      @close="closeMessageDetail"
      :title="currentMessage?.title || 'Message Details'"
      width="500"
    >
      <template v-if="currentMessage">
        <div class="message-detail-header">
          <div class="message-detail-title">{{ currentMessage.title }}</div>
          <div class="message-detail-time">
            <DateFormatter value={currentMessage.time} />
          </div>
        </div>
        <div class="message-detail-content">
          <p>{{ currentMessage.content }}</p>
          <div class="message-detail-actions">
            <a-button type="primary" class="dark-btn" @click="goToDetailPage(currentMessage)">View Details</a-button>
          </div>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { message as antMessage } from 'ant-design-vue';
import { getMyMessageList, getUnreadMessageCount, unmarkMessageAsRead } from '../../api/user';
import { useRouter } from 'vue-router';
import DateFormatter from '@/components/common/DateFormatter.vue';

// 添加router
const router = useRouter();

// 当前选中的tab
const activeTabKey = ref('all');

// 消息数据
const messages = ref([]);
const loading = ref(false);
const total = ref(0);
const unreadCount = ref(0);

// 定时刷新相关
let refreshTimer = null;
const REFRESH_INTERVAL = 60000; // 每分钟刷新一次未读消息数量

// 分页参数
const pagination = ref({
  page: 1,
  pageSize: 10
});

// 抽屉状态
const drawerVisible = ref(false);
const currentMessage = ref(null);

// 获取未读消息数量
const fetchUnreadCount = async () => {
  try {
    const response = await getUnreadMessageCount();
    if (response && response.code === 200) {
      unreadCount.value = response.result || 0;
    }
  } catch (error) {
    // 重复请求被取消是正常情况，不需要显示错误
    // CanceledError 是正常的请求取消，无需处理
    if (error.name !== 'CanceledError') {
      // 仅在非取消错误时进行处理，但不输出到控制台
    }
  }
};

// 设置定时刷新
const setupAutoRefresh = () => {
  // 清除可能存在的旧定时器
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
  
  // 设置新的定时器
  refreshTimer = setInterval(() => {
    fetchUnreadCount();
  }, REFRESH_INTERVAL);
};

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true;
  try {
    // 如果是系统消息标签页，传递数组形式的type参数
    const requestType = activeTabKey.value === '4' ? ['4', '5'] : 
                        activeTabKey.value !== 'all' ? activeTabKey.value : undefined;
    
    const response = await getMyMessageList({
      page: pagination.value.page,
      page_size: pagination.value.pageSize,
      type: requestType
    });
    
    
    if (response && response.code === 200 && response.result) {
      // 处理API返回的数据格式
      if (Array.isArray(response.result.data)) {
        messages.value = response.result.data.map(item => {
          return {
            id: item.id,
            type: item.type, // 默认为系统消息
            title: item.message, // 使用message字段作为标题
            content: item.message_data, // 使用message_data字段作为内容
            time: item.create_time,
            unread: item.reader_id === null, // reader_id为null表示未读
            image: null, // API中没有返回图片字段
            link: null, // API中没有返回链接字段
            message_no: item.message_no // 消息编号
          };
        });
      } else {
        messages.value = [];
      }
      
      // 更新分页信息
      total.value = response.result.total;
      pagination.value.page = response.result.current_page;
      
      // 获取未读消息数量
      fetchUnreadCount();
    } else {
      messages.value = [];
      total.value = 0;
    }
  } catch (error) {
    antMessage.error("Failed to get message list, please try again later");
    messages.value = [];
  } finally {
    loading.value = false;
  }
};

// 监听页码变化
const handlePageChange = (page) => {
  pagination.value.page = page;
  fetchMessages();
};

// 监听每页条数变化
const handleSizeChange = (current, size) => {
  pagination.value.page = 1;
  pagination.value.pageSize = size;
  fetchMessages();
};

// 监听标签页变化
const handleTabChange = () => {
  pagination.value.page = 1;
  fetchMessages();
};

// 根据当前选中的Tab筛选消息
const filteredMessages = computed(() => {
  if (activeTabKey.value === 'all') {
    return [...messages.value].sort((a, b) => new Date(b.time) - new Date(a.time));
  } else if (activeTabKey.value === '4') {
    // 系统消息标签页同时显示type为'4'和'5'的消息
    return [...messages.value]
      .filter(msg => msg.type === '4' || msg.type === '5')
      .sort((a, b) => new Date(b.time) - new Date(a.time));
  } else {
    return [...messages.value]
      .filter(msg => msg.type === activeTabKey.value)
      .sort((a, b) => new Date(b.time) - new Date(a.time));
  }
});

// 根据类型获取消息
const getMessagesByType = (type) => {
  // 如果查询的是系统消息(type为'4')，则同时包含type为'4'和'5'的消息
  if (type === '4') {
    return [...messages.value]
      .filter(msg => msg.type === '4' || msg.type === '5')
      .sort((a, b) => new Date(b.time) - new Date(a.time));
  }
  
  // 其他类型正常过滤
  return [...messages.value]
    .filter(msg => msg.type === type)
    .sort((a, b) => new Date(b.time) - new Date(a.time));
};

// 获取特定类型的消息总数
const getMessageTypeCount = (type) => {
  return getMessagesByType(type).length;
};

// 格式化消息标题
const getMessageTitle = (item) => {
  if (!item || !item.title) {
    return item?.unread ? 'Unnamed Message [Unread]' : 'Unnamed Message';
  }
  return item.unread ? `${item.title} [Unread]` : item.title;
};

// 格式化消息内容
const getMessageContent = (item) => {
  // 确保content存在
  if (!item || !item.content) {
    return '';
  }
  
  // 截断长内容
  return item.content.length > 80 
    ? item.content.substring(0, 80) + '...' 
    : item.content;
};

// 标记消息为已读
const markAsRead = async (msg) => {
  try {
    // 调用unmarkMessageAsRead接口将消息标记为已读
    await unmarkMessageAsRead(msg.id);
    // 标记成功后刷新列表和未读数量
    fetchMessages();
  } catch (error) {
    // 静默处理错误，不在控制台显示
  }
};

// 查看消息详情
const viewMessageDetail = (msg) => {
  currentMessage.value = msg;
  drawerVisible.value = true;
  
  // 如果是未读消息，标记为已读
  if (msg.unread) {
    markAsRead(msg);
  }
};

// 关闭消息详情
const closeMessageDetail = () => {
  drawerVisible.value = false;
  currentMessage.value = null;
};

// 根据消息标题跳转到详情页面
const goToDetailPage = (msg) => {
  // 关闭抽屉
  closeMessageDetail();
  
  // 首先根据消息类型判断
  const msgType = msg.type;
  
  // 根据消息类型进行初步判断
  if (msgType === '1') {
    // 促销消息 - 跳转到促销活动页面
    router.push('/products/promotions');
    return;
  } else if (msgType === '2') {
    // 订单消息 - 跳转到订单页面
    router.push('/user/orders');
    return;
  } else if (msgType === '3') {
    // 信息消息 - 可能是各种信息，继续根据标题判断
  } else if (msgType === '4') {
    // 系统消息 - 可能是系统公告或其他信息，继续根据标题判断
  }
  
  // 如果类型没有明确指向，则根据标题内容判断
  const title = msg.title.toLowerCase();
  
  // 订单相关跳转
  if (title.includes('order') || 
      title.includes('order') || 
      title.includes('purchase') || 
      title.includes('thank you for your purchase') || 
      title.includes('payment')) {
    router.push('/user/orders');
  } 
  // 优惠券相关跳转
  else if (title.includes('coupon') || 
           title.includes('coupon') || 
           title.includes('discount')) {
    router.push('/user/coupons');
  } 
  // 积分相关跳转
  else if (title.includes('point') || 
           title.includes('point') || 
           title.includes('change notice') ||
           title.includes('balance')) {
    router.push('/user/points');
  } 
  // 收藏相关跳转
  else if (title.includes('favorite') || 
           title.includes('favorite') || 
           title.includes('wishlist')) {
    router.push('/user/favorites');
  } 
  // 地址相关跳转
  else if (title.includes('address') || 
           title.includes('address') || 
           title.includes('shipping')) {
    router.push('/user/address');
  } 
  // 默认跳转到用户中心
  else {
    router.push('/user/center');
  }
};

// 页面加载时获取消息列表和未读数量
onMounted(() => {
  fetchMessages();
  fetchUnreadCount();
  setupAutoRefresh();
});

// 组件卸载时清理定时器
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
});
</script>

<style scoped>
.notifications-container {
  padding: 0 10px;
}

.custom-unread-alert {
  display: flex;
  align-items: flex-start;
  padding: 16px 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 16px;
}

.alert-icon {
  margin-right: 12px;
  padding-top: 4px;
}

.alert-title {
  font-weight: bold;
  margin-bottom: 4px;
}

.alert-description {
  color: rgba(0, 0, 0, 0.65);
}

/* 未读消息项样式 */
.unread-list-item {
  background-color: rgba(0, 0, 0, 0.02);
  position: relative;
  border-left: 3px solid #000 !important;
}

.unread-list-item::before {
  content: '';
  position: absolute;
  left: -3px;
  top: 0;
  bottom: 0;
  width: 3px;
  background-color: #000;
}

.unread-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 10px;
  height: 10px;
  margin-right: 4px;
}

/* 消息时间样式 */
.message-time {
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
  margin-left: 8px;
}

/* 分页容器 */
.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.total-count {
  color: rgba(0, 0, 0, 0.45);
}

/* 操作按钮样式 */
.action-btn {
  padding: 0 8px;
  color: #262626;
}

.action-btn:hover {
  color: #000;
}

/* Message Detail Styles */
.message-detail-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 16px;
  margin-bottom: 16px;
}

.message-detail-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.message-detail-time {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.message-detail-content {
  font-size: 14px;
  line-height: 1.6;
}

.message-detail-content p {
  margin-bottom: 16px;
}

.message-detail-actions {
  margin-top: 24px;
}

/* 标题中的未读标识 */
:deep(.ant-list-item-meta-title) {
  display: flex;
  align-items: center;
}

:deep(.unread-list-item .ant-list-item-meta-title) {
  font-weight: 600;
}

.dark-btn {
  background-color: #262626;
  border-color: #262626;
}

.dark-btn:hover {
  background-color: #000;
  border-color: #000;
}

/* 列表样式 */
:deep(.ant-list-item) {
  transition: background-color 0.3s;
}

:deep(.ant-list-item:hover) {
  background-color: #f5f5f5;
}

/* 配合媒体查询的响应式设计 */
@media (max-width: 768px) {
  .pagination-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .total-count {
    margin-top: 8px;
  }
}
</style> 